//
//  YAStatusPictureView.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/7.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import SDWebImage
/// 通知名
let YAStatusPictureViewSelectedNotification = "YAStatusPictureViewSelectedNotification"
/// 选中索引的Key
let YAStatusPictureViewSelectedIndexPathKey = "YAStatusPictureViewSelectedIndexPathKey"
/// 选中图片URL Key
let YAStatusPictureViewSelectedPhotoURLsKey = "YAStatusPictureViewSelectedPhotoURLsKey"
private let YAStatusPictureViewCellID = "YAStatusPictureViewCellID"
class YAStatusPictureView: UICollectionView {
   //MARK:--- 当该视图被赋值VM数据时，计算自己尺寸
    var statusViewModel:YAStatusVM?{
        didSet{
            sizeToFit()
            reloadData()
        }
    }
   //MARK:--- 尺寸自适应将调用这个方法
    override func sizeThatFits(size: CGSize) -> CGSize {
       let layout = collectionViewLayout as! UICollectionViewFlowLayout
       layout.itemSize = CGSize(width:YAStatusPicWidth, height: YAStatusPicWidth)
       let rowCount = 3
       //根据图片数量计算视图
       let count = statusViewModel?.thumbnailURLs?.count ?? 0
        if count == 0 {return CGSizeZero}
        if count == 1 {
            var size = CGSize(width: 150, height: 150)
            //用URL从缓存里去图片
            let key = statusViewModel!.thumbnailURLs![0].absoluteString
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
                size = image.size
            }
            //单独处理过宽或者过窄的图片
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > 300 ? 300 : size.width
            layout.itemSize = size;
            return size
        }
        if count == 4 {
            let w = 2 * YAStatusPicWidth + YAStatusPicMargin
            return CGSize(width: w, height: w)
        }
        let row = CGFloat((count - 1)/rowCount + 1)
        let h = row * YAStatusPicWidth + (row-1)*YAStatusPicMargin
        let w = CGFloat(rowCount) * YAStatusPicWidth + CGFloat(rowCount-1)*YAStatusPicMargin
        
        return CGSize(width: w, height: h)
    }
     //MARK:--- 构造函数
    override init(frame:CGRect,collectionViewLayout layout:UICollectionViewLayout){
        super.init(frame:frame,collectionViewLayout:UICollectionViewFlowLayout())
        backgroundColor = UIColor.whiteColor()
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: YAStatusPicWidth, height: YAStatusPicWidth)
        layout.minimumInteritemSpacing = YAStatusPicMargin
        layout.minimumLineSpacing = YAStatusPicMargin
        registerClass(YAStatusPictureCell.self, forCellWithReuseIdentifier: YAStatusPictureViewCellID)
        dataSource = self
        delegate = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
// MARK: - UICollectionView数据源方法
extension YAStatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate{
    
     //MARK:--- 实现选中图片cell的代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        //添加View测试，点击cell弹出位置
//        let v = UIView(frame: fullScreenRect(indexPath))
//       // v.backgroundColor = UIColor.orangeColor()
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
       //发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(YAStatusPictureViewSelectedNotification, object: self, userInfo: [YAStatusPictureViewSelectedIndexPathKey:indexPath,
            YAStatusPictureViewSelectedPhotoURLsKey:statusViewModel!.bmiddleURLs!
            ])
    }
    //返回指定indexPath 对应cell在屏幕上的坐标位置
    func screenRect(indexPath:NSIndexPath)->CGRect{
        let cell = cellForItemAtIndexPath(indexPath)
        return convertRect(cell!.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    //返回指定 indexPath 对应 图像完全放大后，在屏幕的坐标;通过缩略图先计算好
    func fullScreenRect(indexPath:NSIndexPath)->CGRect{
        let key = statusViewModel!.thumbnailURLs![indexPath.item].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        
        let scale = image.size.height/image.size.width
        let w = UIScreen.mainScreen().bounds.width
        let h = w * scale
        
        var  y = (UIScreen.mainScreen().bounds.height - h) * 0.5
        
        if y < 0 {
            y = 0
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusViewModel?.thumbnailURLs?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YAStatusPictureViewCellID, forIndexPath: indexPath) as! YAStatusPictureCell
        cell.imageURL = statusViewModel!.thumbnailURLs![indexPath.item]
        return cell
    }
}
private class YAStatusPictureCell:UICollectionViewCell
{
     //MARK:--- cell上的View视图
    private lazy var iconView :UIImageView = {
            let iv = UIImageView()
            //设置填充模式
            iv.contentMode = UIViewContentMode.ScaleAspectFill
            iv.clipsToBounds = true
            return iv
        }()
    var imageURL:NSURL?{
        didSet{
            iconView.sd_setImageWithURL(imageURL)//注意这里把图片缓存到本地，方便计算大小
            //通过扩展名判断是否是gif
            gifIconView.hidden = (imageURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif"
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        iconView.addSubview(gifIconView)
        iconView.ff_Fill(self)
        gifIconView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //GIF指示图片
    private lazy var gifIconView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}
